 // 多语言方法
var lang = function(tag) {
    return window.languageResource[tag] || '';
};
$(function() {
    // 初始化区号选择
    var areaCode;
    if ($.cookie("area_code_cookie") != 'undefined') {
        areaCode = $.cookie("area_code_cookie");
        if (areaCode != undefined) {
            $('.areaCode').find('.areaCodeValue').text(areaCode);
        } else {
            $('.areaCode').find('.areaCodeValue').text('86');
        }
    }  
    $('.areaCode').on('click', '.dropdown-menu a', function() {
        var me = $(this),
        value = me.data('value');
        me.parents('.areaCode').find('.areaCodeValue').text(value);
        if ($.cookie("area_code_cookie") != 'undefined') {
            $.cookie('area_code_cookie', value, { expires: 7, path: '/' });
        }
    });    
    //设置语言cookie
    $(".languageSwitch").find("a").click(function(){
       $.cookie('mz_think_language', $(this).attr('data-language'), { expires: 7, path: '/' });
       //重载当前页面
       window.location.reload();
    });

    // 图片懒加载
    if ($('img.lazyload').lazyload !== undefined) {
        $('img.lazyload').lazyload({
            effect: 'fadeIn'
        });
    }
    // 常用正则
    window.commonRegexp = {
        'nameLength15': /^.{1,15}$/,
        'nameLength20': /^.{1,20}$/,
        'nameLength50': /^.{1,50}$/,
        'nameLength255': /.{1,255}/,
        'roomTypePrice': /^([\d]{1,6})(\.[\d]{1,2})?$/,
        'roomTypeCharityPrice': /^[1-9]([0-9]{0,5})(\.[\d]{1,2})?$/,
        'QRMPassword': /^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9]{6,20}$/,
        'email': /^([0-9A-Za-z\-_\.]+)@([0-9A-Za-z]+\.[a-zA-Z0-9]+(\.[a-zA-Z]{2})?)$/,
        'mobile': /^.{1,}$/,
        'globalMobile': /^\d{1,11}$/,
        'password': /^(?=.*?[a-zA-Z])(?=.*?[0-9])[a-zA-Z0-9]{6,20}$/,
        'smsvcode': /^\w{6}$/,
        'numbervcode6': /^\d{6}$/,
        'vcode': /^\w{4}$/,
        'bankNumber': /^\d{16,20}$/,
        'IDCard': /^[a-zA-z0-9]{0,18}$/
    };
    // 正在操作的客栈
    window.currentHotel = $('#navbar-hotel-switch').data('currenthotel');
    window.hotelUsage = $('#navbar-hotel-switch').data('hotelusage');
    window.navbarHotels = {};
    $('#doc-header-brand-dropdown li a').each(function(key, item){
        window.navbarHotels[$(item).data('hotel')] = {name:$(item).text(), enabled: $(item).hasClass('hidden') ? 0:1};
    });
    //切换客栈
    $('#navbar-hotel-switch').delegate('.dropdown-menu li a', 'click', function(e) {
        e.preventDefault();
        // var returnUrl = encodeURIComponent(location.pathname + location.search);
        location.href = '/Home/BookPage/index.html?hotel=' + $(this).data('hotel');
    });
    $('[data-toggle="tooltip"]').tooltip();
    $('#dialogLogin').inputValidate({
        submit: {
            query: '#loginSubmit'
        },
        inputs: [{
            query: '#dialogUserName',
            regexp: window.commonRegexp.mobile,
            message: lang('tip.mobile'),
            emptyMessage: lang('tip.mobileNull')
        }, {
            query: '#dialogPassword',
            regexp: window.commonRegexp.password,
            message: lang('tip.newpasswordwrong'),
            emptyMessage: lang('tip.truePasswordwrongNull')
        }]
    });
    window.symbols = $('#doc-header').data('symbol');
});
// gajax异步请求
// modify trainyao 2016-01-11 增加防重点代码
/* exported ajaxRequest */
var ajaxRequest = function(url, params, method, successcallback, errorcallback, obj) {
    if (obj !== undefined) {
        if (obj.attr('disabled') !== undefined) {
            return false;
        }
        obj.attr('disabled', true);
    }
    if (method === null || method === '') {
        method = 'get';
    }
    $.ajax({
        url: url,
        data: params,
        type: method,
        cache: false,
        dataType: 'json',
        success: function(data) {
            if (obj !== undefined) {
                obj.removeAttr('disabled');
            }
            if (typeof successcallback == 'function') {
                successcallback(data, obj);
            } else {
                window.location.reload();
            }
        },
        error: function(error) {
            if (obj !== undefined) {
                obj.removeAttr('disabled');
            }
            if (typeof errorcallback == 'function') {
                errorcallback(error, obj, defaultErrorHandler);
            } else {
                defaultErrorHandler(error, obj);
            }
        }
    });
};
//一般的ajax请求error处理
/* exported defaultErrorHandler */
var defaultErrorHandler = function(error, obj) {
    if (typeof error.responseJSON == 'undefined') {
        formInlineTip(obj, lang('tip.server'));
    } else if (error.responseJSON.status == 203) {
        formInlineTip(obj, error.responseJSON.info);
        window.setTimeout(dialogLogin(), 1500);
    } else {
        formInlineTip(obj, error.responseJSON.info);
    }
};
//延时跳转到url
/* exported timeoutForward */
var timeoutForward = function(url, time) {
    if (url === undefined || url === '') {
        url = window.location.href;
    }
    if (time === undefined) {
        time = 1500;
    }
    window.setTimeout(function() {
        window.location.href = url;
    }, time);
};
//按钮等待
/* exported timeDisplay */
var timeDisplay = function(objbtn, time) {
    objbtn.addClass('disabled');
    objbtn.attr('disabled', true);
    var i = time;
    var id = window.setInterval(function() {
        i = i - 1;
        objbtn.find('.displayTime').text('(' + i + ')');
        if (i === 0) {
            window.clearInterval(id);
            objbtn.find('.displayTime').text('');
            objbtn.removeClass('disabled');
            objbtn.removeAttr('disabled');
        }
    }, 1000);
};
// 刷新验证码
/* exported refreshVcode */
var refreshVcode = function() {
    var imgCodeObj = $('#imgcode');
    var vcodeUrl = imgCodeObj.attr('src');
    var indexOfQuestionMark = vcodeUrl.indexOf('?');
    if (indexOfQuestionMark !== -1) {
        vcodeUrl = vcodeUrl.substr(0, indexOfQuestionMark);
    }
    var time = new Date().getTime();
    imgCodeObj.attr('src', vcodeUrl + '?' + time);
};
/**
 * 非tooltip类型的提示信息，form-group添加class
 * @param  Object obj  jquery对象
 * @param  string info 提示信息
 * @param  integer type 0表示错误提示，默认为0；1表示成功提示，2表示警告提示。
 */
/* exported formInlineTip */
var formInlineTip = function(obj, info, type) {
    if (type === undefined) {
        type = 0;
    }
    // 检测data中是否定义了显示提示的另一个位置
    var tipObjectStr = $(obj).data('tip-object');
    var tipObject = $(tipObjectStr);
    var hasTipObject = tipObject.length !== 0;
    if (!hasTipObject) {
        tipObject = obj;
    }
    var formGroupObj = tipObject.parents('.form-group');
    var helpBlock = formGroupObj.find('.help-block');
    helpBlock.html(info);
    var tipClass = '';
    switch (type) {
        case 2:
            tipClass = 'has-warning';
            break;
        case 1:
            tipClass = 'has-success';
            break;
        case 0:
            tipClass = 'has-error';
            break;
        default:
            break;
    }
    // 根据tip的类型改变help颜色
    formGroupObj.addClass(tipClass);
    if (hasTipObject) {
        obj.parent().addClass(tipClass);
    }
};
/**
 * 去除表单help-block状态
 * @param  Object obj  jquery对象
 */
/* exported formInlineRight */
var formInlineRight = function(obj) {
    var formGroupObj = obj.parents('.form-group');
    formGroupObj.removeClass('has-error');
    formGroupObj.removeClass('has-warning');
    formGroupObj.removeClass('has-success');
};
/**
 * 对Date的扩展，将 Date 转化为指定格式的String
 * @param  string mask 默认为yyyy-MM-dd
 * @example
 * var customDate = new Date().format("yyyy-MM-dd");
 * @return string
 */
Date.prototype.customFormat = function(mask) {
    if (mask === undefined) {
        mask = 'yyyy-MM-dd';
    }
    var d = this;
    var zeroize = function(value, length) {
        if (!length) {
            length = 2;
        }
        value = String(value);
        for (var i = 0, zeros = ''; i < length - value.length; i++) {
            zeros += '0';
        }
        return zeros + value;
    };
    return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function($0) {
        switch ($0) {
            case 'd':
                return d.getDate();
            case 'dd':
                return zeroize(d.getDate());
            case 'ddd':
                return [
                    'Sun',
                    'Mon',
                    'Tue',
                    'Wed',
                    'Thr',
                    'Fri',
                    'Sat'
                ][d.getDay()];
            case 'dddd':
                return [
                    'Sunday',
                    'Monday',
                    'Tuesday',
                    'Wednesday',
                    'Thursday',
                    'Friday',
                    'Saturday'
                ][d.getDay()];
            case 'M':
                return d.getMonth() + 1;
            case 'MM':
                return zeroize(d.getMonth() + 1);
            case 'MMM':
                return [
                    'Jan',
                    'Feb',
                    'Mar',
                    'Apr',
                    'May',
                    'Jun',
                    'Jul',
                    'Aug',
                    'Sep',
                    'Oct',
                    'Nov',
                    'Dec'
                ][d.getMonth()];
            case 'MMMM':
                return [
                    'January',
                    'February',
                    'March',
                    'April',
                    'May',
                    'June',
                    'July',
                    'August',
                    'September',
                    'October',
                    'November',
                    'December'
                ][d.getMonth()];
            case 'yy':
                return String(d.getFullYear()).substr(2);
            case 'yyyy':
                return d.getFullYear();
            case 'h':
                return d.getHours() % 12 || 12;
            case 'hh':
                return zeroize(d.getHours() % 12 || 12);
            case 'H':
                return d.getHours();
            case 'HH':
                return zeroize(d.getHours());
            case 'm':
                return d.getMinutes();
            case 'mm':
                return zeroize(d.getMinutes());
            case 's':
                return d.getSeconds();
            case 'ss':
                return zeroize(d.getSeconds());
            case 'l':
                return zeroize(d.getMilliseconds(), 3);
            case 'L':
                var m = d.getMilliseconds();
                if (m > 99) {
                    m = Math.round(m / 10);
                }
                return zeroize(m);
            case 'tt':
                return d.getHours() < 12 ? 'am' : 'pm';
            case 'TT':
                return d.getHours() < 12 ? 'AM' : 'PM';
            case 'Z':
                return d.toUTCString().match(/[A-Z]+$/);
                // Return quoted strings with the surrounding quotes removed
            default:
                return $0.substr(1, $0.length - 2);
        }
    });
};
/**
 * 根据需要加减天数，
 * @param  integer interval 负数时是前几天,正数时是后几天
 * @example
 * var diffDays = new Date().customDays(7); 获取7天的后Date对象
 * @return Date
 */
Date.prototype.customDays = function(interval) {
    var thisTime = this.getTime();
    return new Date(thisTime + interval * 86400000);
};
/**
 * 获取两个时间之间的间隔天数
 * @param  Date comparand 被比较的时间对象
 * @example
 * var diffDays = new Date().getDays(getDate('2015-12-01'));
 * @return integer
 */
Date.prototype.getDays = function(comparand) {
    var thisTime = this.getTime();
    var comparandTime = comparand.getTime();
    return parseInt((thisTime - comparandTime) / 86400000);
};
/**
 * 根据传入字符串获取日期对象
 * @param  string input 暂只支持yyyy-MM-dd，2007-04-19格式
 * @return Date
 */
/* exported getDate */
var getDate = function(input) {
    if (!input) {
        return new Date();
    }
    var splitsDate = input.split('-');
    return new Date(splitsDate[1] + '/' + splitsDate[2] + '/' + splitsDate[0]);
};
var dialogLogin = function() {
    var html = '<div class="modal fade" id="dialogLogin"><div class="modal-dialog"><div class="modal-content"><div class="modal-header">';
    html += '<button type="button" class="btn close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
    html += '<h4 class="modal-title"><img src="/Public/uclbrt/image/logo.png?rev=2" /></h4></div>';
    html += '<div class="modal-body"><div class="form-container"><div id="logindialog-form" class="custom-form-body"><form class="form-horizontal"  onsubmit="return false;">';
    html += '<div class="form-group"><label class="col-xs-3 control-label" for="requestUsername">'+lang('commom.moblie')+'</label>';
    html += '<div class="col-xs-6 logindialog-input-container"><input id="dialogUserName" data-tip-object="#logindialog-tip"  class="form-control" type="text" placeholder="'+lang('commom.moblieNum')+'"></div></div>';
    html += '<div class="form-group"><label class="col-xs-3 control-label" for="requestPassword">'+lang('commom.password')+'</label>';
    html += '<div class="col-xs-6 logindialog-input-container"><input id="dialogPassword"  data-tip-object="#logindialog-tip" class="form-control" type="password" placeholder="'+lang('commom.enterPassword')+'"></div></div>';
    html += '<div class="form-group form-tip-group has-warning"> <div id="logindialog-tip" class="help-block text-center"></div></div>';
    html += '<div class="form-group"><div class = "col-xs-12"> <div class = "row" ><div class = "pull-left login-center" ><button type="submit" id="loginSubmit" data-tip-object="#logindialog-tip"  onclick="myLogin()" class="btn-sm btn-primary btn-raised loginSubmit">'+lang('login')+'</button></div><div class = "pull-right" ><a class = "btn-link" href = "/forgetPassword.html" > '+lang('commom.forget') +'</a></div></div></div></div>';
    html += '</form></div></div></div>';
    html += '</div></div>';
    $('body').append(html);
    $('#dialogLogin').modal('show');
};
/**
 * 提示模态框
 * @modify trainyao 2016-01-29 创建
 */
/* exported modalAlert */
var modalAlert = function(message) {
    var modal = $('#alertModal');
    if (modal.get(0) === undefined) {
        $('body').append('<div class="modal fade" id="alertModal" style="background-color:rgba(0,0,0,0.3)"><div class="modal-dialog modal-confirm" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="btn close" data-dismiss="modal"><span>&times;</span></button><h4 class="modal-title">'+lang('commom.hint') +'</h4></div><div class="modal-body"></div><div class="modal-footer"><button type="button" class="btn-primary ulite-js-ripple-effect ulite-js-btn btn-raised"  data-dismiss="modal">'+lang('date.ensure')+'</button></div></div></div></div>');
        modal = $('#alertModal');
    }
    modal.find('.modal-body').text(message);
    modal.modal('show');
};
var modalAlertRF = function(message) {
    var modal = $('#alertRFModal');
    if (modal.get(0) === undefined) {
        $('body').append('<div class="modal fade" id="alertRFModal" style="background-color:rgba(0,0,0,0.3)"><div class="modal-dialog modal-confirm" role="document"><div class="modal-content"><div class="modal-header"><button type="button" class="btn close" data-dismiss="modal"><span>&times;</span></button><h4 class="modal-title">'+lang('commom.hint') +'</h4></div><div class="modal-body"></div><div class="modal-footer"><a href="/Home/PublicPage/cardTip.html?hotel='+window.currentHotel+'" target="_blank" class="btn-primary ulite-js-ripple-effect ulite-js-btn btn-raised">'+lang('date.ensure')+'</a></div></div></div></div>');
        modal = $('#alertRFModal');
    }
    modal.find('.modal-body').text(message);
    modal.modal('show');
};
/* exported successLoginDialogCallback */
var successLoginDialogCallback = function(data) {
    window.location.reload();
};
/* exported errorLoginDialogCallback */
var errorLoginDialogCallback = function(data) {
    if (typeof data.responseJSON == 'undefined') {
        formInlineTip($('#loginSubmit'), lang('tip.networkPoor'), 0);
    } else {
        formInlineTip($('#loginSubmit'), data.responseJSON.info, 0);
    }
};
// dialogLogin();
/* exported myLogin */
function myLogin() {
    var params = {};
    //检查
    params.password = $('#dialogPassword').val().trim();
    params.mobile = $('#dialogUserName').val();
    ajaxRequest('/Home/Public/login', params, 'post', null, null, $('#loginSubmit'));
    return false;
}
/* exported textSize */
function textSize(fontSize, text) {
    var span = document.createElement('span');
    var result = {};
    result.width = span.offsetWidth;
    result.height = span.offsetWidth;
    span.style.visibility = 'hidden';
    document.body.appendChild(span);
    if (typeof span.textContent != 'undefined') {
        span.textContent = text;
    } else {
        span.innerText = text;
    }
    result.width = span.offsetWidth - result.width;
    result.height = span.offsetHeight - result.height;
    span.parentNode.removeChild(span);
    return result;
}
//显示提示信息，obj表示显示信息的对象，info表示显示的内容，direction表示显示位置左上下右，可选1，2，3，4
// 时间输入秒数
/* exported tooltipWrong */
var tooltipWrong = function(obj, info, direction, time) {
    if (direction === undefined) {
        direction = 3;
    }
    if (time === undefined) {
        time = 2;
    }
    obj.tip({
        background: 'rgba(0,0,0,.8)',
        color: '#fff',
        direction: direction,
        time: time,
        content: info
    });
};
$(function(){
	$(function(){
		if(typeof(adHost) != 'undefined' && adHost != ''){
			var josnpUrl = 'http://'+adHost + '/Home/Advertisement/periodical?key=meizhu_web&default_key=meizhu_web_default';
			$.ajax({  
				type: "get",   
				url: josnpUrl,  
				dataType: "jsonp",  
				success: function(data){  
					var $advertisementPic = $('#advertisementPic');
					var remainSecond = data.data.remain_second;
					if(remainSecond>=0){
						$advertisementPic.removeClass('hidden');
						$advertisementPic.find('.advertisement-pic').css("background-image",'url('+data.data.image+")").attr('href',data.data.url);
						var $TotalSecond = parseInt(remainSecond);
						timer($TotalSecond);
					}else{
						$advertisementPic.addClass('hidden');
					}
				},  
				error: function(){  
					 
				}  
			});
		}
	});
});
function timer($TotalSecond){
    var $time = setInterval(function(){
        if($TotalSecond < 0){
            $('#advertisementPic').addClass('hidden');
            clearInterval($time);
        }else{
            $('#advertisementPic').removeClass('hidden');
        }
    var day=0,
        hour=0,
        minute=0,
        second=0;
    if($TotalSecond > 0){
            day = Math.floor($TotalSecond / (60 * 60 * 24));
            hour = Math.floor($TotalSecond / (60 * 60)) - (day * 24);
            minute = Math.floor($TotalSecond / 60) - (day * 24 * 60) - (hour * 60);
            second = Math.floor($TotalSecond) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60);
    }
        if (minute < 10) minute = '0' + minute;
        if (second < 10) second = '0' + second;
        $('#day_show').html(day+lang('commom.sky'));
        $('#hour_show').html('<s></s>'+hour+lang('commom.hour'));
        $('#minute_show').html('<s></s>'+minute+lang('commom.minute'));
        $('#second_show').html('<s></s>'+second+lang('commom.second'));
        $TotalSecond--;
    }, 1000);
}